<script setup>
import GoBackAndSearchNav from "@/components/GoBackAndSearchNav.vue";
import {onBeforeMount, ref, watchEffect} from 'vue'
import {getProductByKw, getProductCategoryAllAPI} from "@/api/product.js";
import {useRoute, useRouter} from 'vue-router'
import NoData from "@/components/NoData.vue";
import ProductItem from "@/components/ProductItem.vue";
import {PRODUCT_ROUTE} from "@/router/routes/product/product.js";
import {areaList} from "@vant/area-data";
import {findProductOptionMinPrice} from "@/utils/XwbUtils.js";
import Null from "@/components/Null.vue";

const route = useRoute()
const router = useRouter()

const productList = ref([])
let productListTemp = []
onBeforeMount(async () => {
  productListTemp = (await getProductByKw(route.query.kw)).map(item => {
    item.minPrice = findProductOptionMinPrice(item.options)
    return item
  })
  productList.value = productListTemp
})
// 是否包邮
const isFreight = ref(0);
const isFreightOption = [
  {text: '全部商品', value: 0},
  {text: '包邮', value: 1},
  {text: '不包邮', value: 2},
];
const order = ref(0);
const orderOption = [
  {text: '默认排序', value: 0},
  {text: '价格升序', value: 1},
  {text: '价格降序', value: 2},
  {text: '销量升序', value: 3},
  {text: '销量降序', value: 4},
];
const category = ref([])
const cate = ref([])
onBeforeMount(async () => {
  category.value = await getProductCategoryAllAPI()
  cate.value = category.value.map(item => ({
    text: item.name,
    value: item.id,
    children: item.subs.map(i => ({text: i.name, value: i.id}))
  }))
})
const cateDropdown = ref(null)
const cateSelected = ref([])
const cateSelectedTemp = ref([])
const onConfirmCate = (selected) => {
  cateSelected.value = selected.selectedValues
  cateSelectedTemp.value = selected.selectedValues
  cateDropdown.value.toggle()
}
const onCancelCate = () => {
  cateDropdown.value.toggle()
}
const address = ref({})
const areaCode = ref('')
const areaCodeTemp = ref('')
const deliveryAddrDropdown = ref(null)
const onConfirmAddr = (selected) => {
  address.value.province = selected.selectedOptions[0].text
  address.value.city = selected.selectedOptions[1].text
  address.value.county = selected.selectedOptions[2].text
  areaCode.value = selected.selectedValues[selected.selectedValues.length - 1]
  areaCodeTemp.value = selected.selectedValues[selected.selectedValues.length - 1]
  deliveryAddrDropdown.value.toggle()
}
const onCancelAddr = () => {
  deliveryAddrDropdown.value.toggle()
}
watchEffect(() => {
  productList.value = productListTemp
  // 要筛选出包邮的书籍商品
  if (isFreight.value === 1) {
    productList.value = productList.value.filter(
        i => i.freight <= 0
    )
  }
  // 要筛选出不包邮的书籍商品
  else if (isFreight.value === 2) {
    productList.value = productList.value.filter(
        i => i.freight > 0
    )
  }
  // 根据书籍商品的价格升序排序
  if (order.value === 1) {
    productList.value = productList.value.sort(
        (a, b) => a.minPrice - b.minPrice
    )
  }
  // 根据书籍商品的价格降序排序
  else if (order.value === 2) {
    productList.value = productList.value.sort(
        (a, b) => b.minPrice - a.minPrice
    )
  }
  // 根据书籍商品的销量升序排序
  else if (order.value === 3) {
    productList.value = productList.value.sort(
        (a, b) => a.sale - b.sale
    )
  }
  // 根据书籍商品的销量降序排序
  else if (order.value === 4) {
    productList.value = productList.value.sort(
        (a, b) => b.sale - a.sale
    )
  }
  // 根据书籍商品的分类进行筛选
  if (cateSelectedTemp.value.length > 0) {
    productList.value = productList.value.filter(
        i => i.productCategoryId === cateSelected.value[0]
            && i.productCategorySubId === cateSelected.value[1]
    )
  }
  // 根据书籍商品的发货地进行筛选
  if (areaCodeTemp.value.length > 0) {
    let addrTemp = ''
    addrTemp += (address.value.province ? address.value.province : '')
    addrTemp += (address.value.city ? '/' + address.value.city : '')
    addrTemp += (address.value.county ? '/' + address.value.county : '')
    productList.value = productList.value.filter(i => i.delivery.includes(addrTemp))
  }
})
const moreDropdown = ref(null)
const resetFilter = () => {
  isFreight.value = 0
  order.value = 0
  cateSelectedTemp.value = []
  areaCodeTemp.value = ''
  productList.value = productListTemp
  moreDropdown.value.toggle()
}

// 前往商品详情页面
const goProductDetail = (idx) => {
  // 获取商品id
  const productId = productList.value[idx].id
  router.push({
    name: PRODUCT_ROUTE,
    query: {
      productId
    }
  })
}
</script>

<template>
  <div class="search-list">
    <GoBackAndSearchNav :title="''" :placeholder="true" :disable-search="false"></GoBackAndSearchNav>
    <van-dropdown-menu swipe-threshold="4">
      <van-dropdown-item v-model="isFreight" :options="isFreightOption"/>
      <van-dropdown-item v-model="order" :options="orderOption"/>
      <van-dropdown-item ref="cateDropdown">
        <template #title>
          分类
        </template>
        <template #default>
          <van-picker v-model="cateSelected" title="分类选择" :columns="cate" @confirm="onConfirmCate" @cancel="onCancelCate"/>
        </template>
      </van-dropdown-item>
      <van-dropdown-item ref="deliveryAddrDropdown">
        <template #title>
          发货地
        </template>
        <template #default>
          <van-area v-model="areaCode" title="选择发货地" :area-list="areaList" @confirm="onConfirmAddr" @cancel="onCancelAddr"/>
        </template>
      </van-dropdown-item>
      <van-dropdown-item ref="moreDropdown">
        <template #title>
          更多
        </template>
        <template #default>
          <div class="p-4">
            <van-button
                block
                round
                color="linear-gradient(to right, #c08eec, #4bb8ec, #c08eec)"
                @click="resetFilter"
            >
              重置筛选条件
            </van-button>
          </div>
        </template>
      </van-dropdown-item>
    </van-dropdown-menu>
    <Null v-if="productList.length <= 0"></Null>
    <div v-else>
      <div
          class="box-border p-2"
          v-for="(product, idx) in productList"
          @click="goProductDetail(idx)"
      >
        <ProductItem :product="product"></ProductItem>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">

</style>